import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import './RenderTreeTitle.less';
import { FormControl, Button, Row, Col} from 'tinper-bee';
import AddTreeNode from './AddTreeNode.jsx';
import { vendorsDanger as danger, vendorsSuccess as success } from 'utils/config.js';
import { toggleStatus, referCheck } from './workprocedure.config.js'
import Popconfirm from 'bee-popconfirm';
import 'bee-popconfirm/build/Popconfirm.css';
export default class RenderTreeTitle extends Component {
	constructor(props){
		super(props);
		this.state={
			item: this.props.item,
			oldSname: this.props.callbackItem.sname === undefined ?
						this.props.item.sname :
						this.props.callbackItem.name,
			show: false,
			editStatus: true,
			isEnd: this.props.item.level==4 ? false : true,
			isTop: this.props.item.pkParent == null ? false : true, // 判断是否为顶层树节点，决定是否展示添加同级按钮
			isSameLevel: false // 是否添加同级
		};
	}
	componentWillReceiveProps (nextProps) {
		this.setState({
			item: nextProps.item,
			isRefer: false,
			isReferSubLevel: false,
		});
	}
	// 添加子级
	createRender = (item, node) => {
		let onCreate = this.props.onCreateRender;
		let { pkProcedure, childProcedure } = item;
		let _me = this;
		if (childProcedure) {
			onCreate(item, true, _me.state.item);
			_me.setState({
				show: true,
				isSameLevel: false,
				isReferSubLevel: false,
			});
			return;
		}
		referCheck({ 'isAjax': 1, 'ieStamp': new Date().getTime(), pkProcedure })
			.then(function (res) {
				if (res.data.resultCode != 'busi_ex') {
					if (res.data.result) {
						_me.setState({
							isReferSubLevel: true
						})
					} else {
						onCreate(item, true, _me.state.item);
						_me.setState({
							show: true,
							isSameLevel: false,
							isReferSubLevel: false,
						});
					}
				} else {
					danger({ 'text': res.data.exMsg })
				}
			})
	}
	createRenderConfirm = (item) =>{
		let onCreate = this.props.onCreateRender;
		onCreate(item, true, this.state.item);
		this.setState({
			show: true,
			isSameLevel: false,
			isReferSubLevel: false,
		});
	}
	// 添加同级
	createSameLevel = (item) => {
		let onCreate = this.props.onCreateSameLevel;
		onCreate(item, true);
		this.setState({
			show: true,
			isSameLevel: true
		});
	}
	// 启用停用
	toggleStatus = (item) => {
		let _me = this;
		let oprflag = item.enableStatus;
		toggleStatus({ ...item, 'isAjax': 1, 'ieStamp': new Date().getTime() })
			.then(function (res) {
				if (res.data.resultCode != 'busi_ex') {
					_me.props.onEnableStatusChanged();
				} else {
					danger({ 'text': res.data.exMsg })
				}
			})
	}
	editRender = (item) => {
		let pkProcedure = item.pkProcedure;
		let _me = this;
		let onEdit = this.props.onEditRender;
		referCheck({ 'isAjax': 1, 'ieStamp': new Date().getTime(), pkProcedure })
			.then(function (res) {
				if (res.data.resultCode != 'busi_ex') {
					if (res.data.result) {
						_me.setState({
							isRefer: true
						})
					} else {
						onEdit(item, true);
						_me.setState({
							editStatus: false
						})
					}
				} else {
					danger({ 'text': res.data.exMsg })
				}
			})
	}
	editRenderConfirm = (item) => {
		let onEdit = this.props.onEditRender;
		onEdit(item, true);
		this.setState({
			editStatus: false,
			isRefer: false,
		})
	}
	deleteRender = (item) => {
		let onDelete = this.props.onDeleteRender;
		onDelete(item);
	}
	nodeChange = (e, type) => {
		let _me = this;
		let item = this.state.item;
		if (type == 'scode') {
			item['scode'] = (item.pcode || '') + this.handlerGetCode(item.pcode ? item.pcode.length : 0, e);
		} else {
			if (e.target.value.length > 50) {
				danger({ 'text': '请限制在50个字符之内！' });
				item['name'] = e.target.value.substring(0, 50);
			} else {
				item['name'] = e.target.value;
			}
		}
		this.setState({
			item: item
		});
	}
	handlerGetCode = (prelen, e) => {
		var codeReg = /^[a-zA-Z0-9_-]+$/i;
		var patternReg = /[^a-zA-Z0-9_-\u4e00-\u9fa5]/g;
		let code = '';
		if (codeReg.test(e.target.value)) {
			if (e.target.value.length + prelen > 20) {
				danger({ 'text': '请限制在20个字符之内！' });
				code = e.target.value.substring(0, 20 - prelen);
			} else {
				code = e.target.value;
			}
		} else {
			if (e.target.value.length + prelen > 20) {
				danger({ 'text': '长度错误：请限制在20个字符之内！, 内容错误：只支持英文、数字、中下划线' });
				code = e.target.value.substring(0, 20 - prelen).replace(patternReg, '');
			} else {
				if (e.target.value.length === 0) {
					code = e.target.value;
				} else {
					danger({ 'text': '内容错误：只支持英文、数字、中下划线' });
					code = e.target.value.replace(patternReg, '');
				}
			}
		}
		return code;
	}
	close = () => {
		let	onClose = this.props.onCloseAddTreeNode;
		onClose();
		this.setState({
			show: false
		});
	}
	onEditCancel = () => {
		let onEditCancel = this.props.onEditCancel;
		onEditCancel(false);
		let oldSname;
		if(this.props.callbackItem.sname === undefined){
			oldSname = this.props.item.sname;
		} else {
			oldSname = this.props.callbackItem.name;
		}
		this.state.item['name'] = oldSname;
		this.state.item['scode'] = this.state.item['key'];
		this.setState({
			editStatus: true
		})
	}
	onEditconfirm = () => {
		let onEditConfirm = this.props.onEditConfirm;
		onEditConfirm(this.state.item, false);
		this.setState({
			editStatus: true
		})
	}
	onAdd = (data, level, item , callback) =>{
		let onAdd = this.props.onAdd;
		onAdd(data, level, item, callback);
	}
	render () {
		let titleIcon, titleInfo, addNode;
		let { enableStatus, childProcedure, pkParent, scode, pcode  } = this.state.item;
		let enableContent = '';
		if (enableStatus) {
			enableContent = '您确定要停用所选数据吗？';
			if(childProcedure){
				enableContent = '您确定要停用所选数据及其所有子孙节点吗？'
			}
		} else {
			enableContent = '您确定要启用所选数据吗？';
		}
		// 控制编辑状态下input输入框显示内容
		if (this.props.editKey == this.state.item.key) {
			titleInfo = 
				<div className="input-group fl clearfix">
					<i className="edit-pcode" className="input-disabled-pcode" style={{ 'display': pkParent ? 'block' : 'none' }}>{pcode}</i>
					<input type="text" id="itemKey" className="code fl input-border-format" value={scode.substr(pcode ? pcode.length : 0)} onChange={(e) => this.nodeChange(e, 'scode')} />
					<input type="text" id="itemKey" className="name fl input-border-format" defaultValue={this.state.item.name} value={this.state.item.name} onChange={this.nodeChange}/>
					<span className="button--state-confirm fl" onClick={this.onEditconfirm}></span>
					<span className="button--state-cancel fl" onClick={this.onEditCancel}></span>
				</div>
		} else {
			titleInfo = <div className={this.state.item.className ? 'text clearfix fl item-bg': 'text clearfix fl '} style={this.state.show? {width:'100%'}:{}}>
							{!this.state.item.childProcedure && <i className="point fl"></i>}
							<span className="title-middle fl">{this.state.item.key} </span>
							<span className="title-middle fl">&nbsp;{this.state.item.name}</span>
						</div>
		}
		// 控制编辑栏的显示
		if (this.props.isHover == this.state.item.key && this.state.editStatus) {
			titleIcon = <div className="clearfix base-btn fl">
				{this.state.isTop && <span className="create-same fl" title="添加同级" onClick={(e) => this.createSameLevel(this.state.item)}></span>}
				{this.state.isEnd &&
					<Popconfirm trigger="click" placement="top"
						content="您所选数据已经被引用了，如果增加下级，则该数据不能被引用。"
						onClose={(e) => this.createRenderConfirm(this.state.item)}
						onClick={(e) => this.createRender(this.state.item)}
						onCancel={this.hideAddSubMsg}
						show={this.state.isReferSubLevel}
					>
						<span className="create fl" title="添加子级"></span>
					</Popconfirm>}
				<Popconfirm trigger="click" placement="top"
					content="您所选数据修改后，历史数据也将一并被修改，确定修改吗？"
					onClose={(e) => this.editRenderConfirm(this.state.item)}
					onClick={(e) => this.editRender(this.state.item)}
					onCancel={this.hideEditMsg}
					show={this.state.isRefer}
				>
					<span className="edit fl" title="编辑"></span>
				</Popconfirm>
				<Popconfirm trigger="click" placement="top" content="您确定删除所选数据吗？" onClose={(e) => this.deleteRender(this.state.item)}>
					<span className="delete fl" title="删除"></span>
				</Popconfirm>
				{
					enableStatus == 1 &&
					<Popconfirm trigger="click" placement="top" content={enableContent} onClose={(e) => this.toggleStatus(this.state.item)}>
						<span className={`stop fl`} title="停用"></span>
					</Popconfirm>
				}
			</div>
		}
		//
		if (this.state.show) {
			addNode = <AddTreeNode onClose={this.close}
								   onAdd={this.onAdd}
								   level={this.props.isPos.length == 2 ? 'second': 'third'}
								   posLength={this.props.isPos.length}
								   className="pos"
								   isSameLevel={this.state.isSameLevel}
								   item={this.state.item}></AddTreeNode>
		}
		return(
			<div className="title-con clearfix">
				{titleInfo}
				{this.state.show || !enableStatus ? '' : titleIcon}
				{this.state.show ? addNode: ''}
				{!enableStatus &&
					<div className="clearfix base-btn fl">
						<Popconfirm trigger="click" placement="top" content={enableContent} onClose={(e) => this.toggleStatus(this.state.item)}>
							<span className={`restart fl`} title={'启用'}></span>
						</Popconfirm>
					</div>
				}
			</div>
		)
	}
}
// 严格检测props值合理性
RenderTreeTitle.PropTypes={
	item: PropTypes.object,
	editKey: PropTypes.string,
	isHover: PropTypes.string,
	isPos: PropTypes.string,
	onCloseAddTreeNode: PropTypes.func,
	onAdd: PropTypes.func,
	callbackItem: PropTypes.object,
	onEditRender: PropTypes.func,
	onCreateRender: PropTypes.func,
	onDeleteRender: PropTypes.func,
	onEditCancel: PropTypes.func,
	onEditConfirm: PropTypes.func,
};